<template>
  <div class="hit-contest-list w">
    <div class="item-rotation">
      <div class="header-card">
        <banner-text :title="'打榜竞技'" :content="'为高校师生提供公平公正的竞赛环境<br>激发高校师生的学术创新和探索热情'" />
        <collect-card
          title="最近参与"
          empty-text="最近没有参与活动哦～"
          footer-btn-text="我的活动"
          :recently-list="recentlyList"
          :go="go"
          @onClick="handleFavorites"
        />
      </div>
    </div>
    <div class="item-list">
      <a-affix :offset-top="120">
        <div class="list-fixed">
          <div class="anchor-box my-scrollbar">
            <div class="screen">
              <div class="screen-box">
                <div
                  v-for="item in AnchorItems"
                  :key="item.labelId"
                  class="cursor-pointer screen-item elliptical-1"
                  :title="item.labelName"
                  :class="{ 'item-checked': selectedItem === item.labelId }"
                  @click="selectItem(item)"
                >
                  {{ item.labelName }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-affix>

      <div class="list-right">
        <div class="case-box">
          <a-spin :spinning="loadingShow" class="full-screen-spin" tip="加载中">
            <div class="case-title">{{ selectedItemTitle }}</div>
            <div class="case-card">
              <activity-card
                v-for="(item, index) in dataList"
                :key="index"
                :data="item"
                card-width="590px"
                @onClickCard="handleClickCard(item as Record)"
                @onClickParticipation="onClickParticipation"
              />
            </div>
            <my-infinite-loading :img-margin-top="'48px'" :empty="dataList?.length === 0" :identifier="identifier" @infinite="loadData" />
          </a-spin>
        </div>
      </div>
    </div>
  </div>

  <participation-modal ref="participationModalRef" @success="participationSuccess" />
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import { ActivityCardData } from '@/components/ActivityCard/index.vue'
  import BannerText from '@/components/BannerText/index.vue'
  import CollectCard, { ListType } from '@/components/CollectCard/index.vue'
  import { hitContestApi, tagManageApi } from '@/services/api'

  import ParticipationModal from '../detail/components/ParticipationModal.vue'
  import { statusMap } from '../options'
  import { DictionaryType, FavoriteResponse, ListData, PageForm, Record, TaskStatus } from '../types'

  const router = useRouter()
  const pageForm = ref<PageForm>({
    projectName: '',
    labelId: '',
    columns: 'createTime',
    order: 'desc',
    offset: 1,
    limit: 8
  })
  const dataList = ref<ActivityCardData[]>([])
  const recentlyList = ref<ListType[]>([])
  const identifier = ref<number>(1)

  const loadData = async ($state: any) => {
    try {
      const {
        data: { records }
      } = (await hitContestApi.list(pageForm.value)) as ListData

      if (records.length < pageForm.value.limit) {
        $state.complete()
      } else {
        pageForm.value.offset++
        $state.loaded()
      }

      const list: ActivityCardData[] = records.map((item: Record) => {
        return {
          id: item.id,
          title: item.name,
          describe: item.description,
          date: `${item.beginTime} - ${item.endTime}`,
          status: statusMap[item.status],
          statusText: item.status,
          label: item.labels || [],
          userNum: item.participantNum,
          isJoin: item.joinStatus
        }
      })
      dataList.value.push(...list)
    } catch (error) {
      $state.error()
    }
  }

  //anchor配置
  const AnchorItems = ref<TaskStatus[]>([])
  const loadingShow = computed(() => {
    return getDictionLoading.value || getFavoriteLoading.value
  })
  //获取项目类型字典
  const { loading: getDictionLoading, runAsync: getAnchorData } = useRequest<ResponseData<DictionaryType[]>>(tagManageApi.list, {
    onSuccess: ({ data }) => {
      AnchorItems.value = [
        {
          labelName: '全部比赛',
          labelId: ''
        },
        ...data.map((item: DictionaryType) => ({ labelName: item.v, labelId: item.id }))
      ]
    }
  })
  /*----------------------------------------- 详情 --------------------------------*/
  const handleClickCard = (item: Record) => {
    window.open(`/hit-contest/detail/${item.id}`)
  }
  const go = (data: { taskId: string }) => {
    console.log('data', data)
    window.open(`/hit-contest/detail/${data.taskId}`)
  }

  //获取我的参与项目列表
  const { loading: getFavoriteLoading, runAsync: getFavoriteData } = useRequest<ResponseData<FavoriteResponse>>(hitContestApi.recentList, {
    onSuccess: ({ data }) => {
      recentlyList.value = [...(data as any)]
      recentlyList.value = (recentlyList.value as any[]).map((item: any) => {
        return {
          name: item.taskName,
          ...item
        }
      })
    }
  })
  const handleFavorites = (item: Record) => {
    console.log('item', item)
    router.push({
      path: `/personal-center`,
      query: { tab: 'hitContest', parentTab: 'activity' }
    })
  }
  const selectedItem = ref<number | string>('')

  const selectItem = (item: TaskStatus) => {
    dataList.value = []
    selectedItem.value = item.labelId
    pageForm.value.labelId = item.labelId
    pageForm.value.offset = 1
    window.scrollTo({
      top: 0
    })
    identifier.value = new Date().getTime()
  }
  const selectedItemTitle = computed(() => {
    const selectedAnchor = AnchorItems.value?.find(item => item.labelId === selectedItem.value)
    return selectedAnchor ? selectedAnchor.labelName : ''
  })

  /* 立即参与 */
  const participationModalRef = ref<InstanceType<typeof ParticipationModal>>()
  const onClickParticipation = (data: ActivityCardData) => {
    participationModalRef.value?.open({ id: data.id })
  }
  const participationSuccess = () => {
    getFavoriteData()
    dataList.value = []
    pageForm.value.offset = 1
    window.scrollTo({
      top: 0
    })
    identifier.value = Date.now()
  }

  // 监听页面滚动
  getAnchorData({
    type: 'rank_type'
  })
  getFavoriteData({
    offset: 1,
    limit: 4
  })
</script>

<style lang="less" scoped>
  .hit-contest-list {
    position: relative;

    .item-rotation {
      margin-top: 24px;
      margin-bottom: 12px;
      width: 100%;
      height: 240px;

      .header-card {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        margin-bottom: 24px;
        width: 100%;
        background: url('@/assets/img/itemcase-img.png');
        border: 1px solid var(--mask-2, rgba(0, 0, 0, 0.1));
        border-radius: 12px;
        box-shadow: 0 1px 5px 0 rgba(66, 132, 237, 0.2);
      }
    }

    .item-list {
      position: relative;
      display: flex;
      justify-content: space-between;
      margin-top: 24px;
      gap: 64px;

      .list-fixed {
        // position: fixed;
        position: static;
        width: 112px;

        .anchor-box {
          // padding-right: 3px;
          overflow-y: auto;
          max-height: 500px;

          .screen {
            position: relative;
            display: flex;
            justify-content: flex-end;
            list-style: none;
            box-sizing: border-box;
            padding-inline-start: 2px;
            // width: 215px;

            .screen-box {
              display: flex;
              justify-content: flex-end;
              // max-width: 112px;
              min-width: 0;
              height: 100%;
              text-align: right;
              flex-direction: column;
              border-right: 1px solid @border1;
              gap: 24px;
              // padding-right: 24px;
              .screen-item {
                padding-right: 24px;
                height: 24px;
                font-size: 16px;
                color: rgba(17, 22, 31, 0.75);
                line-height: 24px; /* 150% */
              }

              .item-checked {
                border-right: 3px solid #649af0;
                color: #1868e9;
                font-weight: 700;
                line-height: 24px; /* 150% */
              }
            }
          }
        }
      }

      .list-left {
        width: 225px;
      }

      .list-right {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 20px;

        .case-box {
          .case-title {
            margin-bottom: 20px;
            font-size: 20px;
            color: rgba(21, 23, 27, 0.95);
            font-weight: 700;
          }

          .case-card {
            display: grid;
            width: 100%;
            grid-template-columns: repeat(auto-fill, minmax(590px, 1fr));
            grid-gap: 20px;

            .card-item {
              width: 354px;
              height: 156px;
            }
          }
        }
      }
    }
  }

  :deep(.ant-anchor-link-title) {
    font-size: 16px;
  }

  :deep(.ant-anchor-link-title-active) {
    font-weight: 700;
  }

  :deep(.ant-anchor) > :not(:last-child) {
    margin-bottom: 24px;
  }
</style>
